package com.core.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 工具类
 */
public class FormatKit {

    //空行
    private static String blankLine;

    //空行
    static {
        StringBuilder r = new StringBuilder(1000);
        for (int i = 0; i < 100; i++) {
            //10个空格
            r.append("          ");
        }
        blankLine = r.toString();
    }


    /**
     * 补充空格，固定长度
     *
     * @param data
     * @param length
     * @return
     */
    public static String format(Object data, Integer length) {
        return formatDirect(data, length, 0);
    }

    /**
     * 补充空格，固定长度
     *
     * @param data
     * @param length
     * @param direct 方向 0 右补全 非0 左补全
     * @return
     */
    public static String formatDirect(Object data, Integer length, Integer direct) {
        String in = "";
        if (data != null) {
            in = data.toString();
        }
        int dateLen = in.length();
        if (length <= dateLen) {
            return in;
        }
        StringBuilder r = new StringBuilder();
        if (direct == 0) {
            r.append(in);
            r.append(blankLine.substring(0, length - dateLen));
        } else {
            r.append(blankLine.substring(0, length - dateLen));
            r.append(in);
        }
        return r.toString();
    }

    /**
     * 锚点对齐
     *
     * @param anchor  对齐锚点
     * @param logList
     * @return
     */
    public static List<String> anchorAlign(Collection<String> logList, String anchor) {

        if (logList == null) {
            return new ArrayList<>();
        }

        //取得对齐位置
        int idx;
        int maxPosition = 0;
        for (String log : logList) {
            idx = log.indexOf(anchor);
            if (idx > maxPosition) {
                maxPosition = log.length();
            }
        }
        //锚点对齐
        List<String> resList = new ArrayList<>(logList.size());
        String tempLog;
        for (String log : logList) {
            tempLog = log.trim();
            idx = tempLog.indexOf(anchor);
            if (idx >= 0) {
                StringBuilder ss = new StringBuilder();
                ss.append(tempLog.substring(0, idx)).append(blankLine.substring(0, maxPosition - idx)).append(tempLog.substring(idx));
                resList.add(ss.toString());
            } else {
                resList.add(tempLog);
            }
        }
        return resList;
    }

}
